const fs = require("fs-extra");
const inquirer = require("inquirer");
const path = require("path");
const chalk = require("chalk");
const ora = require("ora");
const PromptModuleAPI = require("./PromptModuleAPI.js");
const Creator = require("./Creator.js");
const Generator = require("./Ggenerator");
const excuteCommand = require("./utils/excuteCommand");

async function create(name) {
  const creator = new Creator();
  const targetDir = path.join(process.cwd(), name);
  // const spinner = ora("");
  if (fs.existsSync(targetDir)) {
    const { action } = await inquirer.prompt([
      {
        name: "action",
        type: "list",
        message: `Tagrte directory ${chalk.cyan(
          targetDir
        )} is already exists, please choice:`,
        choices: [
          {
            name: "Overwrite",
            value: "overwrite",
          },
          {
            name: "Merge",
            value: "merge",
          },
        ],
      },
    ]);

    if (action === "overwrite") {
      console.log(`\nRemoving ${chalk.cyan(targetDir)}...`);
      await fs.remove(targetDir);
    }

    console.clear();
  }
  const promptModules = getPromptModules();
  const promptAPI = new PromptModuleAPI(creator);

  // 注入features
  promptModules.forEach((module) => {
    module(promptAPI);
  });

  const finalPrompts = creator.getFinalPrompts();
  const answer = await inquirer.prompt(finalPrompts);

  // package.json 文件内容
  const pkg = {
    name,
    version: "0.1.0",
    dependencies: {},
    devDependencies: {},
  };

  // 固定features;
  answer.features.unshift("webpack", "vue");
  const generator = new Generator(pkg, path.join(process.cwd(), name));

  // 生成选中的features文件
  answer.features.forEach((feature) => {
    require(`./generator/${feature}`)(generator, answer);
  });

  await generator.generate();

  // console.log(`\n开始下载依赖\n`);
  // await excuteCommand("yarn", path.join(process.cwd(), name));
  // console.log("\n依赖下载完成! 执行下列命令开始开发：\n");
  // console.log(`cd ${name}`);
  // console.log(`yarn dev`);

  console.log("\n项目初始化成功，请执行下面命令开始运行\n");
  console.log(`cd ${name}`);
  console.log(`yarn`);
  console.log(`yarn dev`);
}

function getPromptModules() {
  return [
    "babel",
    "linter",
    "typescript",
    "router",
    "store" /* , "vuex", "linter" */,
  ].map((file) => require(`./promptModules/${file}`));
}

module.exports = create;
